package com.talos.ums.service.organization;

import com.talos.framework.common.pojo.PageResult;
import com.talos.framework.common.util.object.BeanUtils;
import com.talos.ums.controller.admin.organization.vo.UmsOrganizationPageReqVO;
import com.talos.ums.controller.admin.organization.vo.UmsOrganizationSaveReqVO;
import com.talos.ums.dal.dataobject.organization.UmsOrganizationDO;
import com.talos.ums.dal.mysql.organization.UmsOrganizationMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.talos.framework.common.exception.enums.GlobalErrorCodeConstants.DATA_NOT_FOUND;
import static com.talos.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 组织表 Service 实现类
 *
 * @author ${table.author}
 */
@Service
@Validated
public class UmsOrganizationServiceImpl implements UmsOrganizationService {

    @Resource
    private UmsOrganizationMapper organizationMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOrganization(UmsOrganizationSaveReqVO createReqVO) {
        // 插入
        UmsOrganizationDO organization = BeanUtils.toBean(createReqVO, UmsOrganizationDO.class);
        organizationMapper.insert(organization);
        // 返回
        return organization.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrganization(UmsOrganizationSaveReqVO updateReqVO) {
        // 校验存在
        validateOrganizationExists(updateReqVO.getId());
        // 更新
        UmsOrganizationDO updateObj = BeanUtils.toBean(updateReqVO, UmsOrganizationDO.class);
        organizationMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrganization(Long id) {
        // 校验存在
        validateOrganizationExists(id);
        // 删除
        organizationMapper.deleteById(id);
    }

    private void validateOrganizationExists(Long id) {
        if (organizationMapper.selectById(id) == null) {
            throw exception(DATA_NOT_FOUND);
        }
    }

    @Override
    public UmsOrganizationDO getOrganization(Long id) {
        return organizationMapper.selectById(id);
    }

    @Override
    public PageResult<UmsOrganizationDO> getOrganizationPage(UmsOrganizationPageReqVO pageReqVO) {
        return organizationMapper.selectPage(pageReqVO);
    }

}
